﻿// This file is based on the Microsoft Data Access Application Block for .NET
// For more information please go to 
// http://msdn.microsoft.com/library/en-us/dnbda/html/daab-rm.asp
//===============================================================================

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;
using System.Text;




namespace DAL
{

    /// <summary>
    /// The SqlHelper class is intended to encapsulate high performance, 
    /// scalable best practices for common uses of SqlClient.
    /// </summary>
    public abstract class SqlHelper
    {

        // Hashtable to store cached parameters
        private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// Execute a SqlCommand (that returns no resultset) using an existing SQL Transaction 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  int result = ExecuteNonQuery(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="trans">an existing sql transaction</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>an int representing the number of rows affected by the command</returns>
        public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// Execute a SqlCommand that returns a resultset against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  SqlDataReader r = ExecuteReader(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>A SqlDataReader containing the results</returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);

            // we use a try/catch here because if the method throws an exception we want to 
            // close the connection throw code, because no datareader will exist, hence the 
            // commandBehaviour.CloseConnection will not work
            try
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return rdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

        public static DataTable ExecuteGetTable(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 120;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                cmd.Parameters.Clear();
                return dt;
            }
        }


        public static DataSet ExecuteGetDataSet(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            cmd.CommandTimeout = 120;
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                cmd.Parameters.Clear();
                return ds;
            }
        }


        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against the database specified in the connection string 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="connectionString">a valid connection string for a SqlConnection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
                object val = cmd.ExecuteScalar();
                cmd.Parameters.Clear();
                return val;
            }
        }

        /// <summary>
        /// Execute a SqlCommand that returns the first column of the first record against an existing database connection 
        /// using the provided parameters.
        /// </summary>
        /// <remarks>
        /// e.g.:  
        ///  Object obj = ExecuteScalar(connString, CommandType.StoredProcedure, "PublishOrders", new SqlParameter("@prodid", 24));
        /// </remarks>
        /// <param name="conn">an existing database connection</param>
        /// <param name="commandType">the CommandType (stored procedure, text, etc.)</param>
        /// <param name="commandText">the stored procedure name or T-SQL command</param>
        /// <param name="commandParameters">an array of SqlParamters used to execute the command</param>
        /// <returns>An object that should be converted to the expected type using Convert.To{Type}</returns>
        public static object ExecuteScalar(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {

            SqlCommand cmd = new SqlCommand();

            PrepareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            object val = cmd.ExecuteScalar();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// add parameter array to the cache
        /// </summary>
        /// <param name="cacheKey">Key to the parameter cache</param>
        /// <param name="cmdParms">an array of SqlParamters to be cached</param>
        public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
        {
            parmCache[cacheKey] = commandParameters;
        }

        /// <summary>
        /// Retrieve cached parameters
        /// </summary>
        /// <param name="cacheKey">key used to lookup parameters</param>
        /// <returns>Cached SqlParamters array</returns>
        public static SqlParameter[] GetCachedParameters(string cacheKey)
        {
            SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

            if (cachedParms == null)
                return null;

            SqlParameter[] clonedParms = new SqlParameter[cachedParms.Length];

            for (int i = 0, j = cachedParms.Length; i < j; i++)
                clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

            return clonedParms;
        }

        /// <summary>
        /// Prepare a command for execution
        /// </summary>
        /// <param name="cmd">SqlCommand object</param>
        /// <param name="conn">SqlConnection object</param>
        /// <param name="trans">SqlTransaction object</param>
        /// <param name="cmdType">Cmd type e.g. stored procedure or text</param>
        /// <param name="cmdText">Command text, e.g. Select * from Products</param>
        /// <param name="cmdParms">SqlParameters to use in the command</param>
        private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {

            if (conn.State != ConnectionState.Open)
                conn.Open();

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
                cmd.Transaction = trans;

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter parm in cmdParms)
                    cmd.Parameters.Add(parm);
            }
        }

        public static List<T> DataConvert<T>(DataTable tb)
        {
            List<T> lst = new List<T>();
            DataConvert<T>(tb, ref lst);
            return lst;
        }

        public static List<T> DataConvert<T>(DataTable tb, ref List<T> lst)
        {
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                lst.Add(DataConvert<T>(tb.Rows[i]));
            }
            return lst;
        }

        public static T DataConvert<T>(DataRow row, ref T t)
        {
            var ps = t.GetType().GetProperties();
            var tbColumns = row.Table.Columns;
            foreach (var c in ps)
            {
                var colName = c.Name;
                if (tbColumns.Contains(colName))
                {
                    object nr = row[colName] == DBNull.Value ? null : row[colName];
                    if (nr == null)
                    {
                        c.SetValue(t, nr, null);
                    }
                    else
                    {
                        var nrType = c.PropertyType;
                        if (nrType == typeof(decimal) || nrType == typeof(decimal?))
                        {
                            nr = Convert.ToDecimal(nr);
                        }
                        else if (nrType == typeof(Int64) || nrType == typeof(Int64?))
                        {
                            nr = Convert.ToInt64(nr);
                        }
                        else if (nrType == typeof(double) || nrType == typeof(double?))
                        {
                            nr = Convert.ToDouble(nr);
                        }
                        else if (nrType == typeof(Int32) || nrType == typeof(Int32?))
                        {
                            nr = Convert.ToInt32(nr);
                        }
                        else if (nrType == typeof(Int16) || nrType == typeof(Int16?))
                        {
                            nr = Convert.ToInt16(nr);
                        }
                        c.SetValue(t, nr, null);
                    }

                }
            }
            return t;
        }

        public static T DataConvert<T>(DataRow row)
        {
            var type = typeof(T);
            object obj = type.Assembly.CreateInstance(type.FullName);
            var c = (T)obj;
            DataConvert(row, ref c);
            return c;
        }

        /// <summary>
        /// 根据某个条件得到某列的数据
        /// </summ
        /// ary>
        /// <param name="conn">数据库连接字符串</param>
        /// <param name="columns">表的列的数组</param>
        /// <param name="tableName">表名</param>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public static DataTable GetDataByColumns(string conn, string[] columns, string tableName, string where)
        {
            if (columns == null || columns.Length == 0)
            {
                throw new Exception("columns不能为空或者元素个数为0");
            }
            string cols = " ";
            foreach (var c in columns)
            {
                if (c == "*")
                {
                    cols += c + ",";
                }
                else
                {
                    cols += "[" + c + "],";
                }
            }
            cols = cols.Substring(0, cols.Length - 1);
            string sql = "select" + cols + " from " + tableName + " where " + where;
            return SqlHelper.ExecuteGetTable(conn, CommandType.Text, sql, null);
        }

        /// <summary>
        /// 根据某个条件得到某列的数据
        /// </summary>
        /// <param name="conn">数据库连接字符串</param>
        /// <param name="columns">表的列</param>
        /// <param name="tableName">表名</param>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        public static DataTable GetDataByColumns(string conn, string column, string tableName, string where)
        {
            if (string.IsNullOrEmpty(column))
            {
                throw new Exception("column字段不能为空");
            }
            string[] columns = new string[] { column };
            return GetDataByColumns(conn, columns, tableName, where);
        }

        public static T GetDataByColumns<T>(string conn, string column, string tableName, string where)
        {
            if (string.IsNullOrEmpty(column))
            {
                throw new Exception("column字段不能为空");
            }
            string[] cols = new string[] { column };

            return GetDataByColumns<T>(conn, cols, tableName, where);
        }

        public static T GetDataByColumns<T>(string conn, string[] columns, string tableName, string where)
        {
            DataTable tb = GetDataByColumns(conn, columns, tableName, where);
            if (tb.Rows.Count > 0)
            {
                return DataConvert<T>(tb.Rows[0]);
            }
            else
            {
                return default(T);
            }
        }

        public static List<T> GetDataByColumnsLst<T>(string conn, string column, string tableName, string where)
        {
            if (string.IsNullOrEmpty(column))
            {
                throw new Exception("column字段不能为空");
            }
            string[] cols = new string[] { column };
            return GetDataByColumnsLst<T>(conn, cols, tableName, where);
        }

        public static List<T> GetDataByColumnsLst<T>(string conn, string[] columns, string tableName, string where)
        {
            DataTable tb = GetDataByColumns(conn, columns, tableName, where);
            return DataConvert<T>(tb);
        }

        public static T GetDataByColumns<T>(string conn, string sql, params SqlParameter[] commandParameters)
        {
            DataTable tb = SqlHelper.ExecuteGetTable(conn, CommandType.Text, sql, commandParameters);
            if (tb.Rows.Count > 0)
            {
                return DataConvert<T>(tb.Rows[0]);
            }
            else
            {
                return default(T);
            }
        }

        public static List<T> GetDataByColumnsLst<T>(string conn, string sql, params SqlParameter[] commandParameters)
        {
            DataTable tb = SqlHelper.ExecuteGetTable(conn, CommandType.Text, sql, commandParameters);
            return DataConvert<T>(tb);
        }

        /// <summary>
        /// 类属性转化成字符串
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string PropertiesToString(Type type, List<string> removeIds, Dictionary<string, string> modifyp)
        {
            Dictionary<string, string> modifyp2 = new Dictionary<string, string>();
            if (modifyp != null)
            {
                foreach (var c in modifyp.Keys)
                {
                    modifyp2.Add(c.ToLower(), modifyp[c]);
                }
            }

            if (removeIds != null)
            {
                for (int i = 0; i < removeIds.Count; i++)
                {
                    removeIds[i] = removeIds[i].ToLower();
                }
            }
            var ps = type.GetProperties();
            StringBuilder sb = new StringBuilder();
            foreach (var c in ps)
            {
                string name = c.Name;
                string lname = name.ToLower();
                if (removeIds == null || !removeIds.Contains(lname))
                {
                    if (modifyp2.ContainsKey(lname))
                    {
                        name = modifyp2[lname];
                        sb.Append(name + ",");
                    }
                    else
                    {
                        sb.Append("[" + name + "],");
                    }

                }
            }
            if (sb.Length > 0)
            {
                sb = sb.Remove(sb.Length - 1, 1);
            }
            return sb.ToString();
        }

        public static SqlParameter[] ObjectToSqlParameters(object obj, string[] removeKey)
        {
            //System.
            List<SqlParameter> lst = new List<SqlParameter>();
            var ps = obj.GetType().GetProperties();
            List<string> lstRemove = new List<string>();
            if (removeKey != null)
            {
                foreach (var c in removeKey)
                {
                    lstRemove.Add(c.ToLower());
                }
            }
            foreach (var c in ps)
            {
                if (lstRemove.Contains(c.Name.ToLower()))
                {
                    continue;
                }
                object value = c.GetValue(obj, null);
                if (c.PropertyType == typeof(int) || c.PropertyType == typeof(int?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.Int, value));
                }
                else if (c.PropertyType == typeof(long) || c.PropertyType == typeof(long?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.BigInt, value));
                }
                else if (c.PropertyType == typeof(string))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.VarChar, value));
                }
                else if (c.PropertyType == typeof(bool) || c.PropertyType == typeof(bool?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.Bit, value));
                }
                else if (c.PropertyType == typeof(byte[]))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.Binary, value));
                }
                else if (c.PropertyType == typeof(DateTime) || c.PropertyType == typeof(DateTime?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.DateTime, value));
                }
                else if (c.PropertyType == typeof(decimal?) || c.PropertyType == typeof(decimal) || c.PropertyType == typeof(float)
                    || c.PropertyType == typeof(float?) || c.PropertyType == typeof(double) || c.PropertyType == typeof(double?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.Decimal, value));
                }
                else if (c.PropertyType == typeof(System.Guid) || c.PropertyType == typeof(Guid?))
                {
                    lst.Add(CreateSqlParameter(c.Name, SqlDbType.UniqueIdentifier, value));
                }
            }
            return lst.ToArray();
        }

        public static SqlParameter[] ObjectToSqlParameters(object obj)
        {
            return ObjectToSqlParameters(obj, null);
        }

        private static SqlParameter CreateSqlParameter(string name, SqlDbType dbType, object value)
        {
            if (!name.StartsWith("@"))
            {
                name = "@" + name;
            }
            if (value == null)
            {
                value = DBNull.Value;
            }
            SqlParameter sp = new SqlParameter(name, dbType);
            sp.Value = value;
            return sp;
        }
    }
}